/**
 * #### LRU 缓存类
 * @see https://www.bilibili.com/video/BV1iUPyeXECq?spm_id_from=333.788.videopod.sections&vd_source=9efadbd9bd76b9c14f9589f260a0c1ac
 * @category class
 * @example
 * ```ts
 * const lru = new LRUCache(2);
 * lru.set('a', 1);
 * lru.set('b', 2);
 * lru.get('a'); // 1
 * lru.set('c', 3);
 * lru.get('b'); // null
 * ```
 */
class LRUCache {
  // 定义一个Map类型的缓存
  private cache = new Map();
  // 定义缓存容量
  private capacity: number;

  /***
   * ### LRU缓存构造函数
   * @param capacity 缓存容量，默认为10
   */
  constructor(capacity: number = 10) {
    this.capacity = capacity;
  }

  /**
   * #### 判断缓存中是否存在指定key
   * @param key 要判断的key
   * @returns boolean
   */
  has(key: string) {
    return this.cache.has(key);
  }

  /**
   * 获取指定key的值;
   * @param key 要获取的key
   * @returns
   */
  get(key: string) {
    if (this.cache.has(key)) {
      const value = this.cache.get(key);
      this.cache.delete(key);
      this.cache.set(key, value);
      return value;
    }
    return null;
  }

  /**
   * #### 设置指定key的值，如果缓存已满，则删除最久未使用的key-value
   * @param key 要设置的key
   * @param value 要设置的值
   */
  set(key: string, value: unknown) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    }
    this.cache.set(key, value);
    if (this.cache.size > this.capacity) {
      this.cache.delete(this.cache.keys().next().value);
    }
  }
}

export default LRUCache;
